package com.jcbase.model;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import com.jcbase.core.model.Condition;
import com.jcbase.core.model.Operators;
import com.jcbase.core.pojo.Obj;
import com.jcbase.core.pojo.ObjDetail;
import com.jcbase.core.util.ConnUtil;
import com.jcbase.core.util.IWebUtils;
import com.jcbase.core.view.InvokeResult;
import com.jcbase.core.view.ZtreeView;
import com.jcbase.model.base.BaseSysObj;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;

/**
 * Generated by JFinal.
 */
@SuppressWarnings("serial")
public class SysObj extends BaseSysObj<SysObj> {
    public static final SysObj me = new SysObj();

    public Page<SysObj> getSysObjPage(int page, int rows, String keyword, String orderbyStr) {
	String select = "select * ";
	StringBuffer sqlExceptSelect = new StringBuffer("from sys_obj");
	return this.paginate(page, rows, select, sqlExceptSelect.toString());
    }

    public InvokeResult delete(String bids) {
	List<Integer> ids = new ArrayList<Integer>();
	if (bids.contains(",")) {
	    for (String aid : bids.split(",")) {
		if (StrKit.notBlank(aid)) {
		    ids.add(Integer.valueOf(aid));
		}
	    }
	} else {
	    if (StrKit.notBlank(bids)) {
		ids.add(Integer.valueOf(bids));
	    }
	}
	if (bids.length() > 0) {
	    bids = bids.subSequence(0, bids.length() - 1).toString();
	}
	Set<Condition> conditions = new HashSet<Condition>();
	conditions.add(new Condition("id", Operators.IN, ids));
	this.delete(conditions);
	return InvokeResult.success();
    }

    public List<SysObj> getSysObjNamelist() {
	return this.find("select id,name from sys_obj");
    }

    public InvokeResult save(Integer id, String username, String type, String link, Integer params, String userName,
	    Integer siteId) {
	if (null != id) {
	    SysObj sysObj = this.findById(id);
	    sysObj.set("name", username).set("type", type).set("link", link).set("params", params)
		    .set("user_name", userName).set("site_id", siteId).update();
	} else {
	    SysObj sysObj = new SysObj();
	    sysObj.set("name", username).set("params", params).set("create_time", new Date()).set("type", type)
		    .set("link", link).set("user_name", userName).set("site_id", siteId).save();
	}
	return InvokeResult.success();
    }

    // 获取所有未分配组的用户列表
    public InvokeResult getZtreeViewList() {
	List<SysObj> objList = this.find("select * from sys_obj where ISNULL(group_id)");
	List<ZtreeView> ztreeViews = new ArrayList<ZtreeView>();
	ztreeViews.add(new ZtreeView(10000, null, "root", true));
	for (SysObj sysObj : objList) {
	    ZtreeView ztreeView = new ZtreeView();
	    ztreeView.setId(sysObj.getId());
	    ztreeView.setName(sysObj.getName());
	    ztreeView.setOpen(true);
	    if (sysObj.getInt("pid") == null) {
		ztreeView.setpId(10000);
	    } else {
		ztreeView.setpId(sysObj.getInt("pid"));
	    }
	    ztreeViews.add(ztreeView);
	}
	return InvokeResult.success(JsonKit.toJson(ztreeViews));
    }

    // 插入对象
    public InvokeResult insertObj(List<Obj> objectList) {

	// 是否匹配标记位全部置为0
	Db.update("update  sys_obj  set flag = 0;");
	for (Obj obj : objectList) {
	    List<SysObj> list = SysObj.me.find("select * from sys_obj where name = '" + obj.getName() + "'");
	    if (list != null && list.size() > 0) {
		list.get(0).set("flag", 1).update();
	    } else {
		SysObj sysObj = new SysObj();
		sysObj.set("type", obj.getType()).set("name", obj.getName()).set("link", obj.getLink())
			.set("subject", obj.getSubject()).set("create_time", new Date()).set("flag", 1);
		sysObj.save();
	    }
	}
	// 删除库中不同步的
	List<SysObj> list = SysObj.me.find("select * from sys_obj where flag = 0");
	for (SysObj sysObj : list) {
	    sysObj.deleteById(sysObj.getId());
	}
	return InvokeResult.success("数据库同步成功");
    }

    // 插入对象
    public InvokeResult insertObjBySite(List<ObjDetail> objectList) {

	// 是否匹配标记位全部置为0
	Db.update("update  sys_obj  set flag = 0;");
	for (ObjDetail obj : objectList) {
	    List<SysObj> list = SysObj.me.find("select * from sys_obj where name = '" + obj.getName() + "'");
	    if (list != null && list.size() > 0) {
		list.get(0).set("flag", 1).update();
	    } else {
		SysObj sysObj = new SysObj();
		sysObj.set("type", obj.getType()).set("name", obj.getName()).set("link", obj.getLink())
			.set("subject", obj.getSubject()).set("site_id", obj.getSiteId())
			.set("user_name", obj.getOwnName()).set("create_time", new Date()).set("flag", 1);
		sysObj.save();
	    }
	}
	// 删除库中不同步的
	List<SysObj> list = SysObj.me.find("select * from sys_obj where flag = 0");
	for (SysObj sysObj : list) {
	    sysObj.deleteById(sysObj.getId());
	}
	return InvokeResult.success("数据库同步成功");
    }

    // 获取当前用户所有对象
    public List<SysObj> getGrantObjList(HttpServletRequest request) {
	SysUser user = IWebUtils.getCurrentSysUser(request);

	List<SysUserRole> list = SysRole.me.getRole(request);
	List<SysObj> objList;
	if (SysRole.me.checkIsAdmin(list)) {
	    objList = SysObj.me.getAllList();
	} else {
	    objList = SysObj.me
		    .find("select * from sys_obj where id in (select obj_id from sys_role_obj where role_id in (select role_id from sys_user_role where user_id = "
			    + user.getId() + "))");
	}
	return objList;
    }

    public boolean dataIn(String data_host, String data_user, String data_password) {
	try {
	    Connection conn = ConnUtil.getConn(data_host, data_user, data_password);
	    StringBuffer sql = new StringBuffer();
	    sql.append("SELECT ");
	    sql.append(" \"public\".\"_views\".\"name\" AS view_name,");
	    sql.append("\"public\".\"_workbooks\".\"name\" AS workbooks_name,");
	    sql.append("\"public\".\"_workbooks\".project_name,");
	    sql.append("\"public\".\"_views\".view_url as url");
	    sql.append(" FROM");
	    sql.append("\"public\".\"_views\" ,");
	    sql.append("\"public\".\"_workbooks\" ");
	    sql.append(" WHERE ");
	    sql.append(" \"public\".\"_views\".workbook_id = \"public\".\"_workbooks\".\"id\"");

	    Statement stmt = null;
	    ResultSet rs = null;
	    List<Obj> objList = new ArrayList<Obj>();

	    stmt = conn.createStatement();
	    rs = stmt.executeQuery(sql.toString());
	    while (rs.next()) {
		Obj obj = new Obj();
		obj.setName(rs.getString("view_name"));
		obj.setSubject(rs.getString("workbooks_name"));
		obj.setType(rs.getString("project_name"));
		obj.setLink(rs.getString("url"));
		objList.add(obj);
		System.out.println(String.format("view_name : %s,workbooks_name %s：,project_name: %s,view_url : %s,",
			obj.getName(), obj.getSubject(), obj.getType(), obj.getLink()));
	    }
	    SysObj.me.insertObj(objList);
	} catch (Exception e) {
	    e.printStackTrace();
	    return false;
	}
	return true;
    }

}
